package com.buwei.module.security.application.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.buwei.module.rbac.domain.entity.User;
import com.buwei.module.rbac.domain.repository.UserRepository;

@Service
public class SecurityToolImpl implements SecurityTool{

	@Autowired
	UserRepository userRepository;
	
	/**
	 * @Description : 返回当前登录的用户名，如果没有登录状态，会返回nobody
	 * @return 用户名
	 * ---------------------------------
	 * @Author : Bu Wei
	 * @Date : Created at 2018年3月23日 下午8:18:41
	 */
	public String getCurrentUsername(){
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null || !authentication.isAuthenticated()) {
			return "nobody";
		}
		return authentication.getName();
	}
	
	@Override
	public User getCurrentUser() {
		String username = this.getCurrentUsername();
		return userRepository.findByUsername(username);
	}
}
